package cn.common;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class HandlerExceptionResolver extends SimpleMappingExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        //客户端断开时不要再记了
//        if (ex instanceof org.apache.catalina.connector.ClientAbortException) {
//            return new ModelAndView();
//        }
        //我们自己的已知可控逻辑异常也不记录服务日志
        if (!(ex instanceof CsbitException)) {
            Logger.error("logic error:", ex);
        }

        ModelAndView mv = new ModelAndView();
        // 设置状态码,注意这里不能设置成500，设成500JQuery不会出错误提示 //并且不会有任何反应
        response.setStatus(HttpStatus.OK.value());
        // 设置ContentType
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 避免乱码
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        /// getOutputStream getWriter不能同时调用，否则会出现异常
        // 其他的地方使用的是 getOutputStream
        try (Writer writer = new OutputStreamWriter(response.getOutputStream())) {
            Map<String, Object> map = new HashMap<>();
            map.put("messager", ex.getMessage());
            map.put("error", true);
            writer.write(com.alibaba.fastjson.JSON.toJSONString(map));
            writer.close();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return mv;
    }
}
